const { app, BrowserWindow, dialog } = require('electron');
const path = require('path');
const logger = require('./main/utils/logger');

logger.info('=================================');
logger.info('Application starting...');
logger.info('App path:', app.getAppPath());
logger.info('Is packaged:', app.isPackaged);
logger.info('=================================');

// Import modules
const { initDatabase } = require('./main/database');
const { createWindow } = require('./main/window');
const { registerCaseHandlers } = require('./main/ipc/case');
const { registerDataHandlers } = require('./main/ipc/data');
const { registerFileHandlers } = require('./main/ipc/file');
const { registerConfigHandlers } = require('./main/ipc/config');
const { registerProfileHandlers } = require('./main/ipc/profile');
const { setupSchemaHandlers } = require('./main/ipc/schema');

// Initialize when ready
// Initialize when ready
app.whenReady().then(async () => {
    try {
        const userDataPath = process.env.NODE_ENV === 'development'
            ? path.join(__dirname, '..') // sjfx-vue root
            : path.dirname(app.getPath('exe'));

        const projectRoot = path.join(__dirname, '..');
        logger.info('User data path (Project Root):', projectRoot);

        await initDatabase(projectRoot);

        // 2. Re-initialize logger with configured path (if set)
        try {
            const { getMainKnex } = require('./main/database/knex');
            const knex = getMainKnex();
            const logConfig = await knex('global_configs').where('key', 'log_path').first();
            if (logConfig && logConfig.value) {
                const configuredLogPath = path.join(logConfig.value, 'app.log');
                logger.info(`Applying configured log path: ${configuredLogPath}`);
                await logger.reinitialize(configuredLogPath);
            }
        } catch (err) {
            logger.warn('Failed to apply configured log path, using default:', err.message);
        }

        // 3. Register IPC handlers
        registerCaseHandlers(projectRoot);
        registerDataHandlers();
        registerFileHandlers();
        registerConfigHandlers();
        registerProfileHandlers();
        setupSchemaHandlers();
        const registerAnalysisHandlers = require('./main/ipc/analysis');
        registerAnalysisHandlers();

        // 5. Register Plugins
        const { registerPlugins } = require('./main/plugins/index');
        registerPlugins();

        // 6. Register Search
        const { registerSearchHandlers } = require('./main/ipc/search');
        registerSearchHandlers();

        // 7. Register AI
        const { registerAIHandlers } = require('./main/services/AIService');
        registerAIHandlers();

        // 4. Create Main Window
        createWindow();

    } catch (error) {
        logger.error('Failed to initialize application:', error);
        dialog.showErrorBox('Startup Failed', `App initialization failed: ${error.message}\n\nCheck logs for details.`);
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

app.on('before-quit', async () => {
    const { closeAllConnections } = require('./main/database/knex');
    try {
        await closeAllConnections();
        logger.info('All database connections closed');
    } catch (error) {
        logger.error('Error closing database connections:', error);
    }
});
